[[...path]].page.tsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. import React, { useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import {
  4. isClient, isIPageInfoForEntity, pagePathUtils, pathUtils,
  5. } from '@growi/core';
  6. import type {
  7. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, IUser, IUserHasId,
  8. } from '@growi/core';
  9. import ExtensibleCustomError from 'extensible-custom-error';
  10. import {
  11. NextPage, GetServerSideProps, GetServerSidePropsContext,
  12. } from 'next';
  13. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  14. import dynamic from 'next/dynamic';
  15. import Head from 'next/head';
  16. import { useRouter } from 'next/router';
  17. import superjson from 'superjson';
  18. import { Comments } from '~/components/Comments';
  19. import { PageAlerts } from '~/components/PageAlert/PageAlerts';
  20. // import { useTranslation } from '~/i18n';
  21. import { CurrentPageContentFooter } from '~/components/PageContentFooter';
  22. import { UsersHomePageFooterProps } from '~/components/UsersHomePageFooter';
  23. import type { CrowiRequest } from '~/interfaces/crowi-request';
  24. // import { renderScriptTagByName, renderHighlightJsStyleTag } from '~/service/cdn-resources-loader';
  25. // import { useRendererSettings } from '~/stores/renderer';
  26. // import { EditorMode, useEditorMode, useIsMobile } from '~/stores/ui';
  27. import type { EditorConfig } from '~/interfaces/editor-settings';
  28. import type { CustomWindow } from '~/interfaces/global';
  29. import type { RendererConfig } from '~/interfaces/services/renderer';
  30. import type { ISidebarConfig } from '~/interfaces/sidebar-config';
  31. import type { IUserUISettings } from '~/interfaces/user-ui-settings';
  32. import type { PageModel, PageDocument } from '~/server/models/page';
  33. import type { PageRedirectModel } from '~/server/models/page-redirect';
  34. import type { UserUISettingsModel } from '~/server/models/user-ui-settings';
  35. import { useSWRxCurrentPage, useSWRxIsGrantNormalized, useSWRxPageInfo } from '~/stores/page';
  36. import { useRedirectFrom } from '~/stores/page-redirect';
  37. import {
  38. EditorMode,
  39. useEditorMode, useSelectedGrant,
  40. usePreferDrawerModeByUser, usePreferDrawerModeOnEditByUser, useSidebarCollapsed, useCurrentSidebarContents, useCurrentProductNavWidth,
  41. } from '~/stores/ui';
  42. import { useSetupGlobalSocket, useSetupGlobalSocketForPage } from '~/stores/websocket';
  43. import loggerFactory from '~/utils/logger';
  44. // import { isUserPage, isTrashPage, isSharedPage } from '~/utils/path-utils';
  45. // import GrowiSubNavigation from '../client/js/components/Navbar/GrowiSubNavigation';
  46. // import GrowiSubNavigationSwitcher from '../client/js/components/Navbar/GrowiSubNavigationSwitcher';
  47. import { DescendantsPageListModal } from '../components/DescendantsPageListModal';
  48. import { BasicLayout } from '../components/Layout/BasicLayout';
  49. import GrowiContextualSubNavigation from '../components/Navbar/GrowiContextualSubNavigation';
  50. import DisplaySwitcher from '../components/Page/DisplaySwitcher';
  51. // import { serializeUserSecurely } from '../server/models/serializers/user-serializer';
  52. // import PageStatusAlert from '../client/js/components/PageStatusAlert';
  53. import {
  54. useCurrentUser,
  55. useIsLatestRevision,
  56. useIsForbidden, useIsNotFound, useIsSharedUser,
  57. useIsEnabledStaleNotification, useIsIdenticalPath,
  58. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  59. useDrawioUri, useHackmdUri, useDefaultIndentSize, useIsIndentSizeForced,
  60. useIsAclEnabled, useIsSearchPage, useTemplateTagData,
  61. useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPageId, useCurrentPathname,
  62. useIsSlackConfigured, useRendererConfig,
  63. useEditorConfig, useIsAllReplyShown, useIsUploadableFile, useIsUploadableImage, useCustomizedLogoSrc, useIsContainerFluid,
  64. } from '../stores/context';
  65. import {
  66. CommonProps, getNextI18NextConfig, getServerSideCommonProps, useCustomTitle,
  67. } from './utils/commons';
  68. // import { useCurrentPageSWR } from '../stores/page';
  69. const NotCreatablePage = dynamic(() => import('../components/NotCreatablePage').then(mod => mod.NotCreatablePage), { ssr: false });
  70. const ForbiddenPage = dynamic(() => import('../components/ForbiddenPage'), { ssr: false });
  71. const UnsavedAlertDialog = dynamic(() => import('../components/UnsavedAlertDialog'), { ssr: false });
  72. const GrowiSubNavigationSwitcher = dynamic(() => import('../components/Navbar/GrowiSubNavigationSwitcher'), { ssr: false });
  73. const UsersHomePageFooter = dynamic<UsersHomePageFooterProps>(() => import('../components/UsersHomePageFooter')
  74. .then(mod => mod.UsersHomePageFooter), { ssr: false });
  75. const HandsontableModal = dynamic(() => import('../components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  76. const PageStatusAlert = dynamic(() => import('../components/PageStatusAlert').then(mod => mod.PageStatusAlert), { ssr: false });
  77. const logger = loggerFactory('growi:pages:all');
  78. const {
  79. isPermalink: _isPermalink, isUsersHomePage, isTrashPage: _isTrashPage, isUserPage, isCreatablePage, isTopPage,
  80. } = pagePathUtils;
  81. const { removeHeadingSlash } = pathUtils;
  82. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  83. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  84. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  85. {
  86. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  87. return v?.data != null
  88. && v?.data.toObject != null
  89. && v?.meta != null
  90. && isIPageInfoForEntity(v.meta);
  91. },
  92. serialize: (v) => {
  93. return {
  94. data: superjson.stringify(v.data.toObject()),
  95. meta: superjson.stringify(v.meta),
  96. };
  97. },
  98. deserialize: (v) => {
  99. return {
  100. data: superjson.parse(v.data),
  101. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  102. };
  103. },
  104. },
  105. 'IPageToShowRevisionWithMetaTransformer',
  106. );
  107. const IdenticalPathPage = (): JSX.Element => {
  108. const IdenticalPathPage = dynamic(() => import('../components/IdenticalPathPage').then(mod => mod.IdenticalPathPage), { ssr: false });
  109. return <IdenticalPathPage />;
  110. };
  111. const PutbackPageModal = (): JSX.Element => {
  112. const PutbackPageModal = dynamic(() => import('../components/PutbackPageModal'), { ssr: false });
  113. return <PutbackPageModal />;
  114. };
  115. type Props = CommonProps & {
  116. currentUser: IUser,
  117. pageWithMeta: IPageToShowRevisionWithMeta | null,
  118. // pageUser?: any,
  119. redirectFrom?: string;
  120. // shareLinkId?: string;
  121. isLatestRevision?: boolean,
  122. isIdenticalPathPage?: boolean,
  123. isForbidden: boolean,
  124. isNotFound: boolean,
  125. isNotCreatablePage: boolean,
  126. // isAbleToDeleteCompletely: boolean,
  127. templateTagData?: string[],
  128. templateBodyData?: string,
  129. isSearchServiceConfigured: boolean,
  130. isSearchServiceReachable: boolean,
  131. isSearchScopeChildrenAsDefault: boolean,
  132. isSlackConfigured: boolean,
  133. // isMailerSetup: boolean,
  134. isAclEnabled: boolean,
  135. // hasSlackConfig: boolean,
  136. drawioUri: string,
  137. hackmdUri: string,
  138. noCdn: string,
  139. // highlightJsStyle: string,
  140. isAllReplyShown: boolean,
  141. isContainerFluid: boolean,
  142. editorConfig: EditorConfig,
  143. isEnabledStaleNotification: boolean,
  144. // isEnabledLinebreaks: boolean,
  145. // isEnabledLinebreaksInComments: boolean,
  146. adminPreferredIndentSize: number,
  147. isIndentSizeForced: boolean,
  148. disableLinkSharing: boolean,
  149. rendererConfig: RendererConfig,
  150. // UI
  151. userUISettings?: IUserUISettings
  152. // Sidebar
  153. sidebarConfig: ISidebarConfig,
  154. };
  155. const GrowiPage: NextPage<Props> = (props: Props) => {
  156. // const { t } = useTranslation();
  157. const router = useRouter();
  158. const { data: currentUser } = useCurrentUser(props.currentUser ?? null);
  159. // register global EventEmitter
  160. if (isClient()) {
  161. (window as CustomWindow).globalEmitter = new EventEmitter();
  162. }
  163. // commons
  164. useEditorConfig(props.editorConfig);
  165. useCsrfToken(props.csrfToken);
  166. useCustomizedLogoSrc(props.customizedLogoSrc);
  167. // UserUISettings
  168. usePreferDrawerModeByUser(props.userUISettings?.preferDrawerModeByUser ?? props.sidebarConfig.isSidebarDrawerMode);
  169. usePreferDrawerModeOnEditByUser(props.userUISettings?.preferDrawerModeOnEditByUser);
  170. useSidebarCollapsed(props.userUISettings?.isSidebarCollapsed ?? props.sidebarConfig.isSidebarClosedAtDockMode);
  171. useCurrentSidebarContents(props.userUISettings?.currentSidebarContents);
  172. useCurrentProductNavWidth(props.userUISettings?.currentProductNavWidth);
  173. // page
  174. useIsLatestRevision(props.isLatestRevision);
  175. useIsContainerFluid(props.isContainerFluid);
  176. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  177. useIsForbidden(props.isForbidden);
  178. useIsNotFound(props.isNotFound);
  179. // useIsNotCreatable(props.IsNotCreatable);
  180. useRedirectFrom(props.redirectFrom);
  181. // useShared();
  182. // useShareLinkId(props.shareLinkId);
  183. useIsSharedUser(false); // this page cann't be routed for '/share'
  184. useIsIdenticalPath(false); // TODO: need to initialize from props
  185. // useIsAbleToDeleteCompletely(props.isAbleToDeleteCompletely);
  186. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  187. useIsSearchPage(false);
  188. useTemplateTagData(props.templateTagData);
  189. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  190. useIsSearchServiceReachable(props.isSearchServiceReachable);
  191. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  192. useIsSlackConfigured(props.isSlackConfigured);
  193. // useIsMailerSetup(props.isMailerSetup);
  194. useIsAclEnabled(props.isAclEnabled);
  195. // useHasSlackConfig(props.hasSlackConfig);
  196. useDrawioUri(props.drawioUri);
  197. useHackmdUri(props.hackmdUri);
  198. // useNoCdn(props.noCdn);
  199. useDefaultIndentSize(props.adminPreferredIndentSize);
  200. useIsIndentSizeForced(props.isIndentSizeForced);
  201. useDisableLinkSharing(props.disableLinkSharing);
  202. useRendererConfig(props.rendererConfig);
  203. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  204. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  205. useIsAllReplyShown(props.isAllReplyShown);
  206. useIsUploadableFile(props.editorConfig.upload.isUploadableFile);
  207. useIsUploadableImage(props.editorConfig.upload.isUploadableImage);
  208. const { pageWithMeta, userUISettings } = props;
  209. const pageId = pageWithMeta?.data._id;
  210. const pagePath = pageWithMeta?.data.path ?? (!_isPermalink(props.currentPathname) ? props.currentPathname : undefined);
  211. useCurrentPageId(pageId ?? null);
  212. // useIsNotCreatable(props.isForbidden || !isCreatablePage(pagePath)); // TODO: need to include props.isIdentical
  213. useCurrentPathname(props.currentPathname);
  214. const { data: currentPage } = useSWRxCurrentPage(undefined, pageWithMeta?.data ?? null); // store initial data
  215. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  216. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  217. const { getClassNamesByEditorMode } = useEditorMode();
  218. useSetupGlobalSocket();
  219. useSetupGlobalSocketForPage(pageId);
  220. const shouldRenderPutbackPageModal = pageWithMeta != null
  221. ? _isTrashPage(pageWithMeta.data.path)
  222. : false;
  223. // sync grant data
  224. useEffect(() => {
  225. mutateSelectedGrant(grantData?.grantData.currentPageGrant);
  226. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant]);
  227. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  228. useEffect(() => {
  229. const decodedURI = decodeURI(window.location.pathname);
  230. if (isClient() && decodedURI !== props.currentPathname) {
  231. router.replace(props.currentPathname, undefined, { shallow: true });
  232. }
  233. }, [props.currentPathname, router]);
  234. const classNames: string[] = [];
  235. const isSidebar = pagePath === '/Sidebar';
  236. classNames.push(...getClassNamesByEditorMode(isSidebar));
  237. const isTopPagePath = isTopPage(pageWithMeta?.data.path ?? '');
  238. const isContainerFluidEachPage = currentPage == null || !('expandContentWidth' in currentPage)
  239. ? null
  240. : currentPage.expandContentWidth;
  241. const isContainerFluidDefault = props.isContainerFluid;
  242. const isContainerFluid = isContainerFluidEachPage ?? isContainerFluidDefault;
  243. return (
  244. <>
  245. <Head>
  246. {/*
  247. {renderScriptTagByName('drawio-viewer')}
  248. {renderScriptTagByName('highlight-addons')}
  249. {renderHighlightJsStyleTag(props.highlightJsStyle)}
  250. */}
  251. </Head>
  252. <BasicLayout title={useCustomTitle(props, 'GROWI')} className={classNames.join(' ')} expandContainer={isContainerFluid}>
  253. <div className="h-100 d-flex flex-column justify-content-between">
  254. <header className="py-0 position-relative">
  255. <div id="grw-subnav-container">
  256. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  257. </div>
  258. </header>
  259. <div className="d-edit-none">
  260. <GrowiSubNavigationSwitcher />
  261. </div>
  262. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  263. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  264. <div className="flex-grow-1">
  265. <div id="main" className={`main ${isUsersHomePage(props.currentPathname) && 'user-page'}`}>
  266. <div id="content-main" className="content-main grw-container-convertible">
  267. { props.isIdenticalPathPage && <IdenticalPathPage /> }
  268. { !props.isIdenticalPathPage && (
  269. <>
  270. <PageAlerts />
  271. { props.isForbidden && <ForbiddenPage /> }
  272. { props.isNotCreatablePage && <NotCreatablePage />}
  273. { !props.isForbidden && !props.isNotCreatablePage && <DisplaySwitcher />}
  274. {/* <DisplaySwitcher /> */}
  275. <PageStatusAlert />
  276. </>
  277. ) }
  278. {/* <div className="col-xl-2 col-lg-3 d-none d-lg-block revision-toc-container">
  279. <div id="revision-toc" className="revision-toc mt-3 sps sps--abv" data-sps-offset="123">
  280. <div id="revision-toc-content" className="revision-toc-content"></div>
  281. </div>
  282. </div> */}
  283. </div>
  284. </div>
  285. </div>
  286. { !props.isIdenticalPathPage && !props.isNotFound && (
  287. <footer className="footer d-edit-none">
  288. { pageWithMeta != null && pagePath != null && !isTopPagePath && (
  289. <Comments pageId={pageId} pagePath={pagePath} revision={pageWithMeta.data.revision} />
  290. ) }
  291. { pageWithMeta != null && isUsersHomePage(pageWithMeta.data.path) && (
  292. <UsersHomePageFooter creatorId={pageWithMeta.data.creator._id}/>
  293. ) }
  294. <CurrentPageContentFooter />
  295. </footer>
  296. )}
  297. <UnsavedAlertDialog />
  298. <DescendantsPageListModal />
  299. <HandsontableModal />
  300. {shouldRenderPutbackPageModal && <PutbackPageModal />}
  301. </div>
  302. </BasicLayout>
  303. </>
  304. );
  305. };
  306. function getPageIdFromPathname(currentPathname: string): string | null {
  307. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  308. }
  309. class MultiplePagesHitsError extends ExtensibleCustomError {
  310. pagePath: string;
  311. constructor(pagePath: string) {
  312. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  313. this.pagePath = pagePath;
  314. }
  315. }
  316. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  317. const { model: mongooseModel } = await import('mongoose');
  318. const req: CrowiRequest = context.req as CrowiRequest;
  319. const { crowi } = req;
  320. const { revisionId } = req.query;
  321. const Page = crowi.model('Page') as PageModel;
  322. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  323. const { pageService } = crowi;
  324. let currentPathname = props.currentPathname;
  325. const pageId = getPageIdFromPathname(currentPathname);
  326. const isPermalink = _isPermalink(currentPathname);
  327. const { user } = req;
  328. if (!isPermalink) {
  329. // check redirects
  330. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  331. if (chains != null) {
  332. // overwrite currentPathname
  333. currentPathname = chains.end.toPath;
  334. props.currentPathname = currentPathname;
  335. // set redirectFrom
  336. props.redirectFrom = chains.start.fromPath;
  337. }
  338. // check whether the specified page path hits to multiple pages
  339. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  340. if (count > 1) {
  341. throw new MultiplePagesHitsError(currentPathname);
  342. }
  343. }
  344. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  345. const page = pageWithMeta?.data as unknown as PageDocument;
  346. // add user to seen users
  347. if (page != null && user != null) {
  348. await page.seen(user);
  349. }
  350. // populate & check if the revision is latest
  351. if (page != null) {
  352. page.initLatestRevisionField(revisionId);
  353. await page.populateDataToShowRevision();
  354. props.isLatestRevision = page.isLatestRevision();
  355. }
  356. if (page == null && user != null) {
  357. const templateData = await Page.findTemplate(props.currentPathname);
  358. if (templateData != null) {
  359. props.templateTagData = templateData.templateTags as string[];
  360. props.templateBodyData = templateData.templateBody as string;
  361. }
  362. }
  363. props.pageWithMeta = pageWithMeta;
  364. }
  365. async function injectUserUISettings(context: GetServerSidePropsContext, props: Props): Promise<void> {
  366. const { model: mongooseModel } = await import('mongoose');
  367. const req = context.req as CrowiRequest<IUserHasId & any>;
  368. const { user } = req;
  369. const UserUISettings = mongooseModel('UserUISettings') as UserUISettingsModel;
  370. const userUISettings = user == null ? null : await UserUISettings.findOne({ user: user._id }).exec();
  371. if (userUISettings != null) {
  372. props.userUISettings = userUISettings.toObject();
  373. }
  374. }
  375. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  376. const req: CrowiRequest = context.req as CrowiRequest;
  377. const { crowi } = req;
  378. const Page = crowi.model('Page') as PageModel;
  379. const { currentPathname } = props;
  380. const pageId = getPageIdFromPathname(currentPathname);
  381. const isPermalink = _isPermalink(currentPathname);
  382. const page = props.pageWithMeta?.data;
  383. if (props.isIdenticalPathPage) {
  384. // TBD
  385. }
  386. else if (page == null) {
  387. props.isNotFound = true;
  388. props.isNotCreatablePage = !isCreatablePage(currentPathname);
  389. // check the page is forbidden or just does not exist.
  390. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  391. props.isForbidden = count > 0;
  392. }
  393. else {
  394. props.isNotFound = page.isEmpty;
  395. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  396. if (isPermalink && page.isEmpty) {
  397. props.currentPathname = page.path;
  398. }
  399. // /path/to/page ==> /62a88db47fed8b2d94f30000
  400. if (!isPermalink && !page.isEmpty) {
  401. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  402. if (!isToppage) {
  403. props.currentPathname = `/${page._id}`;
  404. }
  405. }
  406. }
  407. }
  408. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  409. // const req: CrowiRequest = context.req as CrowiRequest;
  410. // const { crowi } = req;
  411. // const UserModel = crowi.model('User');
  412. // if (isUserPage(props.currentPagePath)) {
  413. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  414. // if (user != null) {
  415. // props.pageUser = JSON.stringify(user.toObject());
  416. // }
  417. // }
  418. // }
  419. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  420. const req: CrowiRequest = context.req as CrowiRequest;
  421. const { crowi } = req;
  422. const {
  423. appService, searchService, configManager, aclService, slackNotificationService, mailService,
  424. } = crowi;
  425. props.isSearchServiceConfigured = searchService.isConfigured;
  426. props.isSearchServiceReachable = searchService.isReachable;
  427. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  428. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  429. // props.isMailerSetup = mailService.isMailerSetup;
  430. props.isAclEnabled = aclService.isAclEnabled();
  431. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  432. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  433. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  434. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  435. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  436. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  437. props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  438. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  439. // props.isEnabledLinebreaks = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks');
  440. // props.isEnabledLinebreaksInComments = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments');
  441. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  442. props.editorConfig = {
  443. upload: {
  444. isUploadableFile: crowi.fileUploadService.getFileUploadEnabled(),
  445. isUploadableImage: crowi.fileUploadService.getIsUploadable(),
  446. },
  447. };
  448. props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  449. props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  450. props.rendererConfig = {
  451. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  452. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  453. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  454. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  455. plantumlUri: process.env.PLANTUML_URI ?? null,
  456. blockdiagUri: process.env.BLOCKDIAG_URI ?? null,
  457. // XSS Options
  458. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:xss:isEnabledPrevention'),
  459. attrWhiteList: crowi.xssService.getAttrWhiteList(),
  460. tagWhiteList: crowi.xssService.getTagWhiteList(),
  461. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  462. };
  463. props.sidebarConfig = {
  464. isSidebarDrawerMode: configManager.getConfig('crowi', 'customize:isSidebarDrawerMode'),
  465. isSidebarClosedAtDockMode: configManager.getConfig('crowi', 'customize:isSidebarClosedAtDockMode'),
  466. };
  467. }
  468. /**
  469. * for Server Side Translations
  470. * @param context
  471. * @param props
  472. * @param namespacesRequired
  473. */
  474. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  475. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  476. props._nextI18Next = nextI18NextConfig._nextI18Next;
  477. }
  478. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  479. const req = context.req as CrowiRequest<IUserHasId & any>;
  480. const { user } = req;
  481. const result = await getServerSideCommonProps(context);
  482. // check for presence
  483. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  484. if (!('props' in result)) {
  485. throw new Error('invalid getSSP result');
  486. }
  487. const props: Props = result.props as Props;
  488. if (props.redirectDestination != null) {
  489. return {
  490. redirect: {
  491. permanent: false,
  492. destination: props.redirectDestination,
  493. },
  494. };
  495. }
  496. if (user != null) {
  497. props.currentUser = user.toObject();
  498. }
  499. try {
  500. await injectPageData(context, props);
  501. }
  502. catch (err) {
  503. if (err instanceof MultiplePagesHitsError) {
  504. props.isIdenticalPathPage = true;
  505. }
  506. else {
  507. throw err;
  508. }
  509. }
  510. await injectUserUISettings(context, props);
  511. await injectRoutingInformation(context, props);
  512. injectServerConfigurations(context, props);
  513. await injectNextI18NextConfigurations(context, props, ['translation']);
  514. return {
  515. props,
  516. };
  517. };
  518. export default GrowiPage;